package com.util.httpRequest;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kuibu on 16/1/24.
 */
public class HttpRequest {
    private static final Logger LOGGER = Logger.getLogger(HttpRequest.class);

    /**
     * 发送GET请求
     *
     * @param urlStr
     * @return
     */
    public static String sendGet(String urlStr) {
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();

            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            httpURLConnection.setConnectTimeout(20 * 1000);
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream imgInputStream = httpURLConnection.getInputStream();
            byte[] data = readInputStream(imgInputStream);
            String json = new String(data);
            return json;
        } catch (Exception exception) {
            LOGGER.error("发送Get请求出错...", exception);
            return "Ops,Error occurred...";
        }
    }


    /**
     * 从输入流中获取数据
     *
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 根据手机号获取手机号码归属地
     *
     * @param telnumber
     * @return
     */
    public static Map<String, Object> getUserTelRegion(String telnumber) {
        String requestUrl = "http://apis.juhe.cn/mobile/get?phone=" + telnumber + "&dtype=json&key=0e966145bc22a83bb7532fda47250d29";
        String result = sendGet(requestUrl);

        JSONObject jsonObject = JSONObject.parseObject(result);
        Map<String, Object> map = new HashMap<>();
        map.put("province", jsonObject.getJSONObject("result").getString("province"));
        map.put("city", jsonObject.getJSONObject("result").getString("city"));
        return map;
    }

}
